var TREE_ROOT_CATALOG = 'tree-root-catalog';

function wrapperData(data) {
    var _data = data;
    if(data.length) {
        _data = {
            'section': [],
            'title': '目录',
            'content_id': TREE_ROOT_CATALOG
        };
        for(var i = 0; i < data.length; i ++) {
            _data['section'].push({
                'content_id': data[i]['content_id'],
                'section': data[i]['section'],
                'title': data[i]['title'],
                '_id': data[i]['_id']
            });
        }
    }
    var _output = {};
    modifyData(_data, _output);
    return _output;
}

function modifyData(data, output) {
    if(!data) {
        return;
    }
    var _data = {};
    var doc_id = '';
    if('_id' in data) {
        doc_id = [' data-doc="', data['_id'], '"'].join('');
    }
    _data['name'] = ['<div', doc_id, ' data-id="', data['content_id'],'">', data['title'], '</div>'].join('');
    if('section' in data && data['section'].length > 0) {
        _data['type'] = 'folder';
    }
    else {
        _data['type'] = 'item'
    }
    if(_data['type'] == 'folder') {
        _data['additionalParameters'] = {
            'children': {}
        };
        for (var i = 0; i < data['section'].length; i++) {
            modifyData(data['section'][i], _data['additionalParameters']['children']);
        }
    }
    output[data['content_id']] = _data;
}

function dsHelpCatalog(options) {
    this._data  = wrapperData(options.data);
    // this._delay = options.delay;
}
dsHelpCatalog.prototype.data = function(options, callback) {
    var self = this;
    var $data = null;
    if(!("name" in options) && !("type" in options)){
        $data = this._data;
        callback({
            data: $data
        });
        return;
    }
    else if("type" in options && options.type == "folder") {
        if("additionalParameters" in options && "children" in options.additionalParameters) {
            $data = options.additionalParameters.children;
        }
        else {
            $data = {};
        }
    }
    if($data != null) {
        setTimeout(function() {
            callback({
                'data': $data
            });
            setTimeout(function() {
                var $tree_box = $('#left-nav-tree .left-nav-body .nav-tree-box');
                $tree_box.find('.tree-folder-header').each(function(i, item) {
                    var header_width = $(item).width();
                    var icon_width = $(item).find('i[class*="icon-"]').width();
                    $(item).find('.tree-folder-name').width(header_width - icon_width - 16);
                });
                $tree_box.find('.tree-folder-content').each(function(i, item) {
                    var _width = $(item).find('.tree-item').width();
                    $(item).find('.tree-item-name').width(_width);
                });
                adjustWH();
            }, 50);
        }, 50);
    }
};

function showCatalogTree(data) {
    $('#left-nav-tree .left-nav-body .nav-tree-box').ace_tree({  
        dataSource: new dsHelpCatalog({
            data: data
        }),
        multiSelect: false,
        loadingHTML: '<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>',
        'open-icon': 'icon-minus',
        'close-icon': 'icon-plus',
        'selectable': false,
        'selected-icon': null,
        'unselected-icon': null,
        cacheItems: false ,
        folderSelect: false
    });
}

function requestHelpCatalog(_url) {
    $.ajax({
        url: _url,
        type: 'POST',
        dataType: 'json',
        success: function(data) {
            if(data && data.length > 0) {
                showCatalogTree(data);
            }
        },
        error: function(data) {
            try {
                console.log(data);
            }
            catch (ex) {}
        }
    });
}

function adjustWH() {
    var $container = $('.page_container .content_wrapper');
    var c_w = $container.width();
    var $nav_box = $('#left-nav-tree .left-nav-body .nav-tree-box');
    $nav_box.height($(window).height()-$nav_box.offset().top);
    $('#viewer-wrapper').height($(window).height()-$('#viewer-wrapper').offset().top);
    $('#viewer-wrapper').width(c_w - $nav_box.width() - 20 - 20);
    var c_h=$(window).height()-$('#viewer-wrapper').offset().top-$(".mce-container.mce-toolbar").height()-74;
    $(".mce-edit-area.mce-container").height(c_h);
    $(".mce-edit-area.mce-container>iframe").height(c_h);
}

function getID($elem) {
    var _id = $elem.attr('data-id');
    if(_id) {
        return _id;
    }
    var $p_elem = $elem.parents('.tree-folder-header,.tree-item');
    if($p_elem.length < 1) {
        if($elem.hasClass('tree-folder-header') || $elem.hasClass('tree-item')) {
            $p_elem = $elem;
        }
    }
    if($p_elem.length > 0) {
        return $p_elem.find('div[data-id]').attr('data-id');
    }
    return undefined;
}

function bindItemClick(_url, set_data) {
    if(!$(document.body).data('data-content')) {
        $(document.body).data('data-content', {});
    }
    $("#left-nav-tree .left-nav-body .nav-tree-box").off('click').on('click', function(eve) {
        var $elem = $(eve.target);
        var _id = getID($elem);
        if(!_id) {
            return;
        }
        if(_id == TREE_ROOT_CATALOG) {
            $(document.body).data('data-content')[_id] = '目录';
        }
        var $self = $(this);
        var $me = $self.find(['div[data-id="', _id,'"]'].join(''));
        setTimeout(function() {
            bindToolip(); // ace-tree会重新生成dom，所以需要重新绑定事件
        }, 250);
        if(!$me.hasClass('current-item')) {
            $('#left-nav-tree .left-nav-body .nav-tree-box div[data-id].current-item').removeClass('current-item')
            $me.addClass('current-item');
            var old_data = $(document.body).data('data-content')[_id];
            if(old_data) {
                set_data(old_data);
            }
            else {
                $.ajax({
                    url: _url,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        'help_id': _id
                    },
                    success: function(data) {
                        // console.log(data);
                        if(data.error == 0) {
                            $(document.body).data('data-content')[data._id] = data.content;
                            set_data(data.content);
                        }
                    },
                    error: function(data) {
                        try {
                            console.log(data);
                        }
                        catch (ex) {}
                    }
                });
            }
        }
    });
}

function showOneItem(is_editor) {
    var $first = $('.tree-folder .tree-folder-header .tree-folder-name div[data-id]');
    var is_set = undefined;
    if(is_editor) {
        is_set = $('#content-editor').data('editor-instance');
    }
    else {
        is_set = $('#viewer-wrapper').find('.content-viewer').length > 0;
    }
    if($first.length < 1 || !is_set) {
        var load_img_timeout = $(document.body).data('show_first_timeout');
        if(load_img_timeout) {
            clearTimeout(load_img_timeout);
        }
        load_img_timeout = setTimeout(arguments.callee, 100);
        $(document.body).data('show_first_timeout', load_img_timeout);
    }
    else {
        $first.trigger('click');
    }
}

function bindToolip() {
    var $nav_box = $('#left-nav-tree .left-nav-body .nav-tree-box');
    var $items = $nav_box.find('div[data-id]')
    $items.each(function(i, item) {
        var $self = $(item);
        $self.popover('hide');
        var tmp_id = 'id_' + Math.random().toString().replace('.', '');
        // console.log(tmp_id);
        var $tmp = $(['<div>', $self.html(), '</div>'].join('')).css({
            'visibility': 'hidden',
            'display': 'inline-block'
        }).attr('id', tmp_id);
        $(document.body).append($tmp);

        var $tmp_real = $('#' + tmp_id);
        if($tmp_real.innerWidth() > $self.width()) {
            $self.popover({
                content: $self.html(),
                delay: {
                    "show": 150,
                    "hide": 350
                },
                trigger: 'manual',
                placement: 'right',
                container: '.page_container .content_wrapper'
            });
        }
        $tmp_real.remove();

    });
    $nav_box.off('mouseover').on('mouseover', function(eve) {
        var $elem = $(eve.target);
        var _id = getID($elem);
        if(_id) {
            var $obj = $nav_box.find(['div[data-id="', _id, '"]'].join(''));
            $obj.popover('show');
            $obj.parent().off('mouseleave').on('mouseleave', function() {
                $(this).find('div[data-id]').popover('hide');
            });
            if($obj.hasClass('current-item')) {
                $obj.parent().off('mouseover').on('mouseover', function() {
                    $(this).find('div[data-id]').popover('show');
                });
            }
        }
    });
}
var MENU_EVENT_LEVEL = {
    TOP: 1,
    NODE: 2,
    NONE: 3
};

function showMessage(_text, _type, _timeout, _btn) {
    if(!_text) {
        return;
    }
    if(!_type) {
        // success, info, warning, error
        _type = 'info';
    }
    if(!_timeout) {
        _timeout = 3000; // milliseconds
    }
    if(_btn === undefined || _btn === null) {
        _btn = true;
    }
    else {
        _btn = !!_btn;
    }
    // https://www.tinymce.com/docs/advanced/creating-custom-notifications/
    tinymce.activeEditor.notificationManager.open({
        text: _text,
        type: _type,
        timeout: _timeout,
        closeButton: _btn
    });
}

function addOneHelp(_content) {
    $.ajax({
        url: '/admin/help_add_one/',
        type: 'POST',
        data: {
            content: _content
        },
        dataType: 'json',
        success: function(data) {
            var _type = 'error';
            if(data.error == 0) {
                _type = 'success';
                requestNavData(true);
            }
            showMessage(data.desc, _type);
        },
        error: function(data) {
            try {
                console.log(data);
            }
            catch (ex) {}
        }
    });
}

function addHelpNode(_content, _parent, _section, _doc) {
    $.ajax({
        url: '/admin/help_add_node/',
        type: 'POST',
        data: {
            content: _content,
            parent: _parent,
            section: _section,
            doc: _doc
        },
        dataType: 'json',
        success: function(data) {
            console.log('data')
            var _type = 'error';
            if(data.error == 0) {
                _type = 'success';
                requestNavData(true);
            }
            showMessage(data.desc, _type);
        },
        error: function(data) {
            try {
                console.log(data);
            }
            catch (ex) {}
        }
    });
}

function renameHelpNode(_content, _node_id, _section, _doc) {
    $.ajax({
        url: '/admin/help_rename_node/',
        type: 'POST',
        data: {
            content: _content,
            node: _node_id,
            section: _section,
            doc: _doc
        },
        dataType: 'json',
        success: function(data) {
            console.log('data')
            var _type = 'error';
            if(data.error == 0) {
                _type = 'success';
                requestNavData(true);
            }
            showMessage(data.desc, _type);
        },
        error: function(data) {
            try {
                console.log(data);
            }
            catch (ex) {}
        }
    });
}

function delOneHelp(_node_id, _section, _doc) {
    $.ajax({
        url: '/admin/help_del_node/',
        type: 'POST',
        data: {
            node: _node_id,
            section: _section,
            doc: _doc
        },
        dataType: 'json',
        success: function(data) {
            var _type = 'error';
            if(data.error == 0) {
                _type = 'success';
                requestNavData(true);
            }
            showMessage(data.desc, _type);
        },
        error: function(data) {
            try {
                console.log(data);
            }
            catch (ex) {}
        }
    });
}

function nearParent($elem, css_class) {
    var $parent = $elem.parent();
    while(!$parent.hasClass(css_class)) {
        $parent = $parent.parent();
        if($parent.hasClass('nav-tree-box') || $parent.is(document.body)) {
            $parent = {
                'length': 0
            }
            break;
        }
    }
    return $parent;
}

/**
 * 迭代查找父级节点
 * $elem 当前操作的节点
 * _output 输出参数
 */
function loopParent($elem, _output, _callback) {
    if($elem.attr('data-id')) {
        if($elem.attr('data-doc')) {
            _output['doc'] = $elem.attr('data-doc');
            return;
        }
        else {
            if(!_callback) {
                var _class;
                if($elem.parent().hasClass('tree-item-name')) {
                    _class = 'tree-item';
                }
                else if($elem.parent().hasClass('tree-folder-name')) {
                    _class = 'tree-folder';
                }
                if(_class) {
                    var $pp = nearParent($elem, _class);
                    if($pp.length > 0) {
                        var _count = _output['count'] + 1;
                        _output['count'] = _count;
                        _output[_count] = $elem;
                        _output['index'].unshift($pp.index());
                        return arguments.callee($pp.parent(), _output, true);
                    }
                }
            }
        }
    }
    var $data_node;
    if($elem.parent().hasClass('tree-folder-name') || $elem.parent().hasClass('tree-item-name')) {
        $data_node = nearParent($elem, 'tree-folder-content');
    }
    else if($elem.hasClass('tree-folder-content')) {
        $data_node = $elem;
    }
    var $next;
    if($data_node && $data_node.length > 0) {
        $next = nearParent($data_node, 'tree-folder-content');
        var $node = $data_node.siblings('.tree-folder-header').find('.tree-folder-name div[data-id]');
        if($node.length > 0 && $node.attr('data-id') != TREE_ROOT_CATALOG) {
            var _doc = $node.attr('data-doc');
            var _count = _output['count'] + 1;
            _output['count'] = _count;
            _output[_count] = $node;
            if(_doc) {
                _output['doc'] = _doc;
                return;
            }
            var $pp = nearParent($node, 'tree-folder');
            if($pp.length > 0) {
                _output['index'].unshift($pp.index())
            }
        }
    }
    else {
        $next = $elem.parent();
    }
    if($next.hasClass('nav-tree-box') || $next.is(document.body)) {
        return;
    }
    arguments.callee($next, _output, true);
}

function bindTreeContextMenu() {
    var $tree_box = $("#left-nav-tree .left-nav-body .nav-tree-box");
    $tree_box.prop('event-level', MENU_EVENT_LEVEL.NONE);
    $(document.body).data('current-edit-node-data', {});
    $tree_box.removeProp('node-id');
    var top_level_func = function(key, options) {
        var mel = options.$trigger.prop('event-level');
        return mel == MENU_EVENT_LEVEL.TOP;
    };
    var node_level_func = function(key, options) {
        var mel = options.$trigger.prop('event-level');
        var node_id = options.$trigger.prop('node-id');
        return mel == MENU_EVENT_LEVEL.NODE && node_id != TREE_ROOT_CATALOG;
    };
    var menu_items = {
        add_top_node: {
            name: '添加导航',
            icon: 'add',
            visible: top_level_func,
            callback: function(key, options) {
                dialog.prompt('新建导航', '添加导航<small>(字数: 2~32)</small>', function(_val) {
                    addOneHelp(_val);
                }, function() {
                    // console.log(key + ': cancel');
                }, true, function(_val) {
                    return (/.{2,32}/).test(_val);
                });
                return true;
            }
        },
        add_node: {
            name: '添加子节点',
            icon: 'add',
            visible: node_level_func,
            callback: function(key, options) {
                var _id = options.$trigger.prop('node-id');
                $(document.body).data('current-edit-node-data', _id);
                var _value = $([
                    'div[data-id="', _id, '"]'].join('')
                ).html();
                dialog.prompt(_value, '添加子节点<small>(字数: 2~32)</small>', function(_val) {
                    var _parent = $(document.body).data('current-edit-node-data');
                    var $tree_box = $("#left-nav-tree .left-nav-body .nav-tree-box");
                    var $elem = $tree_box.find(['div[data-id="', _parent, '"]'].join(''));
                    var _output = {
                        'count': 0,
                        'index': []
                    };
                    loopParent($elem, _output);
                    console.log(_output)
                    var _section = _output['index'].join(',');
                    var _doc = _output['doc'];
                    addHelpNode(_val, _parent, _section, _doc);
                }, function() {
                    // console.log(key + ': cancel');
                }, true, function(_val) {
                    return (/.{2,32}/).test(_val);
                });
                return true;
            }
        },
        rename_node: {
            name: '重命名',
            icon: 'edit',
            visible: node_level_func,
            callback: function(key, options) {
                var _id = options.$trigger.prop('node-id');
                $(document.body).data('current-edit-node-data', _id);
                var _value = $([
                    'div[data-id="', _id, '"]'].join('')
                ).html();
                dialog.prompt(_value, '重命名<small>(字数: 2~32)</small>', function(_val) {
                    var _node_id = $(document.body).data('current-edit-node-data');
                    var $tree_box = $("#left-nav-tree .left-nav-body .nav-tree-box");
                    var $elem = $tree_box.find(['div[data-id="', _node_id, '"]'].join(''));
                    var _output = {
                        'count': 0,
                        'index': []
                    };
                    loopParent($elem, _output);
                    console.log(_output)
                    var _section = _output['index'].join(',');
                    var _doc = _output['doc'];
                    renameHelpNode(_val, _node_id, _section, _doc);
                }, function() {
                    console.log(key + ': cancel');
                }, true, function(_val) {
                    return (/.{2,32}/).test(_val);
                });
                return true;
            }
        },
        del_node: {
            name: '删除',
            icon: 'delete',
            visible: node_level_func,
            callback: function(key, options) {
                var _id = options.$trigger.prop('node-id');
                $(document.body).data('current-edit-node-data', _id);
                var _value = $([
                    'div[data-id="', _id, '"]'
                ].join('')).html();
                var _msg = [
                    '确定要删除<code>',
                        _value,
                    '</code>吗?'
                ].join('');
                dialog.confirm(_msg, '删除确认', function() {
                    var _node_id = $(document.body).data('current-edit-node-data');
                    var $tree_box = $("#left-nav-tree .left-nav-body .nav-tree-box");
                    var $elem = $tree_box.find(['div[data-id="', _node_id, '"]'].join(''));
                    var _output = {
                        'count': 0,
                        'index': []
                    };
                    loopParent($elem, _output);
                    console.log(_output)
                    var _section = _output['index'].join(',');
                    var _doc = _output['doc'];
                    delOneHelp(_node_id, _section, _doc);
                }, function() {
                    console.log(key + ': cancel');
                }, true);
                return true;
            }
        }
    };
    var common_options = {
        appendTo: '.page_container .content_wrapper',
        autoHide: false,
        items: menu_items,
        animation: {
            duration: 110,
            show: 'slideDown',
            hide: 'fadeOut'
        },
        callback: function(key, options) {
            return true;
        },
        events: {
            show: function(options) {
                return true;
            },
            hide: function(options) {
                return true;
            }
        }
    };
    var menu_options = {
        selector: "#left-nav-tree .left-nav-body .nav-tree-box",
        trigger: 'right',
        build: function($trigger, eve) {
            var _id = getID($(eve.target));
            if(_id) {
                $trigger.prop('event-level', MENU_EVENT_LEVEL.NODE);
                $trigger.prop('node-id', _id);
            }
            else if($(eve.target).hasClass('nav-tree-box')) {
                $trigger.prop('event-level', MENU_EVENT_LEVEL.TOP);
            }
            else {
                $trigger.prop('event-level', MENU_EVENT_LEVEL.NONE);
            }
            return menu_options;
        }
    };
    var opt_config = $.extend(true, {}, menu_options, common_options);
    $.contextMenu(opt_config);
}
//获取图片大小
function getImageSize(url, callback) {
    var img = document.createElement('img');

    function done(width, height) {
        if (img.parentNode) {
            img.parentNode.removeChild(img);
        }

        callback({width: width, height: height});
    }

    img.onload = function() {
        done(Math.max(img.width, img.clientWidth), Math.max(img.height, img.clientHeight));
    };

    img.onerror = function() {
        done();
    };

    var style = img.style;
    style.visibility = 'hidden';
    style.position = 'fixed';
    style.bottom = style.left = 0;
    style.width = style.height = 'auto';

    document.body.appendChild(img);
    img.src = url;
}
function setupEditor() {
    $('#my_form').find('input[name="help-image-data"]').on('change', function() {
        $('#my_form').ajaxSubmit({
            dataType:"json",
            success: function(data) {
                if (data.error==0) {
                    var target=$("body").data("help-image-target");
                    var imgurl=window.location.protocol+"//"+window.location.host+data.url;
                    $("#"+target).val(imgurl);
                    getImageSize(imgurl, function(data) {
                        if (data.width && data.height) {
                            var imguploaddialog= $("#"+target).closest(".mce-container.mce-window[aria-label='Insert/edit image'][role='dialog']");
                            imguploaddialog.find("input.mce-textbox[aria-label='Width']").val(data.width);
                            imguploaddialog.find("input.mce-textbox[aria-label='Height']").val(data.height);
                        }
                    });
                }
                else{
                     $.bootstrapGrowl(data.desc, {
                        type: 'danger', //('danger', 'info', 'error', 'success')
                        align: 'center', //('left', 'right', or 'center')
                        offset: {
                            from: 'top',
                            amount: 155
                        },
                        width: 'auto', //(integer, or 'auto')
                        allow_dismiss: false,
                        stackup_spacing: 30,
                        delay: 1500
                    });
                }
                
            }
        });
    });
    var _h = $('.page_container .content_wrapper').height() - 186;
    if(_h < 100) {
        _h = 100;
    }
    tinymce.init({
        selector: '#content-editor',
        schema: 'html5',
        theme: 'modern',
        skin: 'lightgray',
        height: _h,
        min_height: 100,
        min_width: 100,
        langeage: 'zh_CN',
        language_url: GLOBAL.TINYMCE_LANG_zh_CN,
        inline: false,
        menubar: false,
        statusbar: true,
        plugins: [
            'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
            'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
            'save table contextmenu directionality emoticons template paste textcolor',
            // 'imagetools',
            'fullpage colorpicker codesample'
        ],
        external_plugins: {},
        // code_dialog_height: 300,
        // code_dialog_width: 350,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'lower-alpha,lower-roman,upper-alpha,upper-roman',
        toolbar: [
            'undo redo searchreplace',
            'formatselect fontselect fontsizeselect', //styleselect
            'bold italic underline strikethrough subscript superscript hr removeformat pagebreak',
            'alignleft aligncenter alignright alignjustify',
            'bullist numlist outdent indent',
            'charmap insertdatetime link media template',
            'forecolor backcolor emoticons',
            'codesample code preview print restoredraft',
            'mySave image'
        ].join(' | '),
        image_advtab: true,
        imagetools_toolbar: "rotateleft rotateright | flipv fliph | editimage imageoptions",
        images_upload_url: '/courseware/upload/',
        content_save_url: '/admin/help_save/',
        imagetools_proxy: '/admin/help_catalog/',
        paste_data_images: true,
        images_upload_handler: function(blobInfo, success, failure) {
            success("data:" + blobInfo.blob().type + ";base64," + blobInfo.base64());
        },
        file_browser_callback: function(field_name, url, type, win) {
            if(type=='image') {
                $(document.body).data("help-image-target",field_name);
                $('#my_form input').click();
            }
        },
        automatic_uploads: false,
        convert_urls: false,
        force_p_newlines: true,
        remove_trailing_brs: false,
        forced_root_block_attrs: {
            'class': 'myclass',
            'data-something': 'my data'
        },
        templates: [
            {
                title: 'Test template 1',
                content: 'Test 1'
            }, {
                title: 'Test template 2',
                content: 'Test 2'
            }
        ],
        setup: function (editor) {
            $('#content-editor').data('editor-instance', editor);
            editor.addCommand('my_mceSave', function() {
                // https://www.tinymce.com/docs/api/class/tinymce.editor/#getcontent
                var _content = editor.getBody().innerHTML;
                var _url = editor.getParam('content_save_url', null);
                var _id = $('#left-nav-tree .left-nav-body .nav-tree-box div[data-id].current-item').attr('data-id');
                if(_content && _url && _id) {
                    if(_id == TREE_ROOT_CATALOG) {
                        editor.setContent('目录');
                        editor.save();
                        editor.setDirty(!1);
                        editor.fire('dirty');
                        showMessage('目录是自动生成的节点，不支持保存', 'info');
                    }
                    else {
                        $.ajax({
                            url: _url,
                            type: 'POST',
                            data: {
                                content: _content,
                                id: _id
                            },
                            dataType: 'json',
                            success: function(data) {
                                var _type = 'error'; // success, info, warning, error
                                if(data.error == 0) {
                                    $(document.body).data('data-content')[_id] = _content;
                                    editor.save();
                                    editor.setDirty(!1);
                                    editor.fire('dirty');
                                    _type = 'success';
                                }
                                showMessage(data.desc, _type);
                            },
                            error: function(data) {
                                try {
                                    console.log(data);
                                }
                                catch (ex) {}
                            }
                        });
                    }
                }
                else {
                    showMessage('has error', 'error');
                }
            });
            editor.addButton('mySave', {
                text: 'Save',
                icon: 'save',
                cmd: 'my_mceSave',
                disabled: !0,
                onPostRender: function() {
                    var self = this;
                    editor.on('nodeChange dirty', function () {
                        self.disabled(editor.getParam('save_enablewhendirty', !0) && !editor.isDirty());
                        if(!editor.isDirty()) {
                            self.active(false);
                        }
                    })
                }
            });
        },
        init_instance_callback : function(editor) {
            showOneItem(true);
        }
    });
}

function set_data(_content) {
    var editor = $('#content-editor').data('editor-instance');
    editor.setContent(_content);
    editor.save();
    editor.undoManager.clear();
}

function requestNavData(re_call) {
    var $nav_left = $("#left-nav-tree .left-nav-body");
    if(re_call) {
        $nav_left.find(".nav-tree-box").remove();
    }
    if($nav_left.find(".nav-tree-box").length < 1) {
        $nav_left.append('<div class="tree tree-unselectable nav-tree-box"></div>');
    }
    requestHelpCatalog('/admin/help_catalog/');
    /* 导航滚动条美化 */
    setTimeout(function() {
        $("#left-nav-tree .left-nav-body .nav-tree-box").niceScroll({
            cursorcolor: "#7F848A",
            cursorborder: "1px solid transparent"
        });
    }, 200);
    bindItemClick('/admin/help_content/', set_data);
    setTimeout(function() {
        bindToolip();
        if(re_call) {
            showOneItem();
        }
    }, 250);
    bindTreeContextMenu();
}

$(document).ready(function() {
    $("#left-nav-tree .left-nav-body").append('<div class="tree tree-unselectable nav-tree-box"></div>');
    var $container = $(document.body);
    document.addEventListener(screenfull.raw.fullscreenchange,function(){
        if(screenfull.isFullscreen) {
            $(".header_wkj").addClass("screen-full-hide");
            $("#niceScroll").addClass("screen-full-hide");
            $container.addClass("screen-full-body");
            $(".page_container.sidebar_expanded").addClass("screen-full-padding");
            $(".content_wrapper").addClass("screen-full-container");
        }
        else {
            $(".header_wkj").removeClass("screen-full-hide");
            $("#niceScroll").removeClass("screen-full-hide");
            $container.removeClass("screen-full-body");
            $(".content_wrapper").removeClass("screen-full-container");
            $(".page_container.sidebar_expanded").removeClass("screen-full-padding");
        }
        adjustWH();
        $(window).trigger("resize");
    });
    $('#screenfull-button').click(function() {
        var $self = $(this);
        // refer: https://github.com/sindresorhus/screenfull.js
        if (screenfull.enabled) {
            screenfull.toggle($container[0]);
        }
    });
    requestNavData();
    adjustWH();
    $(window).resize(function() {
        adjustWH();
    });
    $('#niceScroll a[toggle-collapse="collapse"]').click(function() {
        setTimeout(function() {
            adjustWH();
        }, 100);
    });
    setupEditor();
});